import React, { useState, useEffect, useRef, useCallback } from 'react';
import { List, Input, Button, Avatar, Badge, Popup, Toast } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import EmojiPicker from 'emoji-picker-react';
import axios from 'axios';

// 配置axios默认URL
axios.defaults.baseURL = 'http://localhost:3000';

// 默认头像
const DEFAULT_AVATAR = '';

const Message = () => {
  const [messages, setMessages] = useState([]);
  const [inputMsg, setInputMsg] = useState('');
  const [ws, setWs] = useState(null);
  const [currentChat, setCurrentChat] = useState(null);
  const [users, setUsers] = useState([]);
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const messagesEndRef = useRef(null);
  const navigate = useNavigate();
  const wsRef = useRef(null);

  // 敏感词列表
  const sensitiveWords = ['笨蛋', '傻瓜', '脑残'];

  // 更新消息列表的函数
  const addMessage = useCallback((newMessage) => {
    console.log('添加新消息:', newMessage);
    setMessages(prevMessages => {
      // 检查消息是否已存在
      const messageExists = prevMessages.some(msg => 
        msg.from === newMessage.from && 
        msg.to === newMessage.to && 
        msg.content === newMessage.content &&
        msg.timestamp === newMessage.timestamp
      );

      if (messageExists) {
        console.log('消息已存在，不重复添加');
        return prevMessages;
      }

      console.log('添加新消息到列表');
      return [...prevMessages, newMessage];
    });
  }, []);

  // 获取当前用户信息
  useEffect(() => {
    const userStr = localStorage.getItem('data');
    console.log('Retrieved user data from localStorage:', userStr);
    
    if (!userStr) {
      console.log('No user data found in localStorage');
      Toast.show({
        content: '请先登录',
        icon: 'fail'
      });
      navigate('/login');
      return;
    }

    try {
      const user = JSON.parse(userStr);
      console.log('Parsed user data:', user);
      
      if (!user || !user._id) {
        console.log('Invalid user data:', user);
        Toast.show({
          content: '用户信息无效',
          icon: 'fail'
        });
        navigate('/login');
        return;
      }
      setCurrentUser(user);
      console.log('Set current user:', user);
    } catch (error) {
      console.error('解析用户信息失败:', error);
      navigate('/login');
    }
  }, [navigate]);

  // 获取用户列表
  const fetchUsers = useCallback(async () => {
    if (!currentUser?._id) {
      console.log('No current user ID, skipping fetchUsers');
      return;
    }

    try {
      console.log('Fetching users for ID:', currentUser._id);
      const response = await axios.get(`/api/messages/contacts/${currentUser._id}`);
      console.log('Fetched users:', response.data);
      setUsers(response.data);
    } catch (error) {
      console.error('获取联系人列表失败:', error);
      Toast.show({
        content: '获取联系人列表失败',
        icon: 'fail'
      });
    }
  }, [currentUser]);

  // 获取聊天记录
  const fetchMessages = useCallback(async (targetUserId) => {
    if (!currentUser?._id) {
      console.log('No current user ID, skipping fetchMessages');
      return;
    }

    try {
      console.log('获取与用户的聊天记录:', targetUserId);
      console.log('Current user ID:', currentUser._id);
      const response = await axios.get(`/api/messages/chat/${currentUser._id}/${targetUserId}`);
      console.log('获取到的聊天记录:', response.data);
      setMessages(response.data || []);
    } catch (error) {
      console.error('获取聊天记录失败:', error);
      console.error('Error details:', error.response || error);
      Toast.show({
        content: '获取聊天记录失败',
        icon: 'fail'
      });
    }
  }, [currentUser]);

  // 初始化WebSocket连接
  const initWebSocket = useCallback(() => {
    if (!currentUser?._id) return null;

    try {
      console.log('正在建立WebSocket连接...');
      const newWs = new WebSocket(`ws://localhost:3000?userId=${currentUser._id}`);
      newWs.onopen = () => {
        console.log('WebSocket连接已建立');
        fetchUsers();
      };

      newWs.onmessage = async (event) => {
        addMessage(event.data)
        console.log('收到WebSocket消息:', event.data);
        
        try {
          const data = JSON.parse(event.data);
          console.log('解析后的消息数据:', data);

          if (data.type === 'chat') {
            // 检查消息是否与当前聊天相关
            const isRelevantMessage = 
              (data.from === currentChat && data.to === currentUser._id) || 
              (data.from === currentUser._id && data.to === currentChat);

            console.log('当前聊天对象:', currentChat);
            console.log('消息是否相关:', isRelevantMessage);

            if (isRelevantMessage) {
              console.log('添加消息到当前聊天');
              addMessage(data)

              // 如果是接收到的消息，标记为已读
              if (data.from === currentChat) {
                try {
                  await axios.post(`/api/messages/read`, {
                    from: data.from,
                    to: currentUser._id
                  });
                } catch (error) {
                  console.error('标记消息已读失败:', error);
                }
              }
            } else {
              console.log('消息不属于当前聊天窗口');
            }

            // 更新用户列表（未读消息数）
            fetchUsers();
          }
        } catch (error) {
          console.error('处理WebSocket消息失败:', error);
        }
      };

      newWs.onclose = () => {
        console.log('WebSocket连接已关闭');
        setTimeout(() => {
          console.log('尝试重新连接WebSocket...');
          const reconnectWs = initWebSocket();
          if (reconnectWs) {
            wsRef.current = reconnectWs;
            setWs(reconnectWs);
          }
        }, 3000);
      };

      newWs.onerror = (error) => {
        console.error('WebSocket错误:', error);
      };

      return newWs;
    } catch (error) {
      console.error('WebSocket连接失败:', error);
      return null;
    }
  }, [currentUser, currentChat, fetchUsers, addMessage]);

  // 当用户信息更新时，初始化WebSocket
  useEffect(() => {
    if (currentUser?._id) {
      fetchUsers();
      const newWs = initWebSocket();
      if (newWs) {
        wsRef.current = newWs;
        setWs(newWs);
      }
    }

    return () => {
      if (wsRef.current) {
        wsRef.current.close();
      }
    };
  }, [currentUser, fetchUsers, initWebSocket]);

  // 监听当前聊天对象变化
  useEffect(() => {
    if (currentChat) {
      console.log('切换聊天对象:', currentChat);
      fetchMessages(currentChat);
    }
  }, [currentChat, fetchMessages]);

  // 自动滚动到最新消息
  useEffect(() => {
    console.log('消息列表更新，滚动到底部');
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // 过滤敏感词;
  const filterSensitiveWords = (text) => {
    let filteredText = text;
    sensitiveWords.forEach(word => {
      const regex = new RegExp(word, 'g');
      filteredText = filteredText.replace(regex, '*'.repeat(word.length));
    });
    return filteredText;
  };

  const sendMessage = async () => {
    if (!inputMsg.trim() || !currentChat || !currentUser?._id) return;

    const messageData = {
      from: currentUser._id,
      to: currentChat,
      content: filterSensitiveWords(inputMsg),
      timestamp: new Date().toISOString()
    };

    try {
      console.log('发送新消息:', messageData);

      // 先更新本地消息列表
      addMessage(messageData);
      setInputMsg('');

      // 发送消息到后端
      await axios.post('/api/messages', messageData);
      
      // 通过WebSocket发送消息
      if (ws?.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
          type: 'chat',
          ...messageData
        }));
      } else {
        console.error('WebSocket未连接，尝试重新连接...');
        const newWs = initWebSocket();
        if (newWs) {
          wsRef.current = newWs;
          setWs(newWs);
          // 等待连接建立后发送消息
          newWs.onopen = () => {
            newWs.send(JSON.stringify({
              type: 'chat',
              ...messageData
            }));
          };
        }
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      Toast.show({
        content: '发送消息失败',
        icon: 'fail'
      });
      // 发送失败时从消息列表中移除该消息
      setMessages(prevMessages => 
        prevMessages.filter(msg => 
          msg.from !== messageData.from || 
          msg.to !== messageData.to || 
          msg.content !== messageData.content ||
          msg.timestamp !== messageData.timestamp
        )
      );
    }
  };

  const handleChatSelect = async (userId) => {
    console.log('选择聊天对象:', userId);
    setCurrentChat(userId);
    if (!currentUser?._id) return;

    try {
      await axios.post(`/api/messages/read`, {
        from: userId,
        to: currentUser._id
      });
      fetchUsers();
    } catch (error) {
      console.error('标记已读失败:', error);
    }
  };

  const onEmojiClick = (emojiObject) => {
    setInputMsg(prevInput => prevInput + emojiObject.emoji);
    setShowEmojiPicker(false);
  };

  return (
    <div style={{ display: 'flex', height: 'calc(100vh - 50px)' }}>
      {currentUser ? (
        <>
          {/* 用户列表 */}
          <div style={{ width: '30%', borderRight: '1px solid #eee', overflowY: 'auto' }}>
            <List header="消息列表">
              {users.map(user => (
                <List.Item
                  key={user._id}
                  prefix={<Badge content={user.unread || null}><Avatar src={user.image || DEFAULT_AVATAR} /></Badge>}
                  description={user.unread ? `${user.unread}条未读` : ''}
                  onClick={() => handleChatSelect(user._id)}
                  className={currentChat === user._id ? 'active-chat' : ''}
                >
                  {user.username}
                </List.Item>
              ))}
            </List>
          </div>

          {/* 聊天区域 */}
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
            {currentChat ? (
              <>
                <div style={{ flex: 1, padding: '10px', overflowY: 'auto' }}>
                  {messages.map((msg, index) => (
                    <div
                      key={`${msg.timestamp}-${index}`}
                      style={{
                        textAlign: msg.from === currentUser._id ? 'right' : 'left',
                        margin: '10px 0'
                      }}
                    >
                      <div
                        style={{
                          display: 'inline-block',
                          padding: '8px 12px',
                          borderRadius: '18px',
                          background: msg.from === currentUser._id ? '#1677ff' : '#f5f5f5',
                          color: msg.from === currentUser._id ? '#fff' : '#333',
                          maxWidth: '70%',
                          wordBreak: 'break-word'
                        }}
                      >
                        {msg.content}
                      </div>
                      <div style={{ fontSize: '12px', color: '#999', marginTop: '4px' }}>
                        {new Date(msg.timestamp).toLocaleTimeString()}
                      </div>
                    </div>
                  ))}
                  <div ref={messagesEndRef} />
                </div>

                {/* 输入区域 */}
                <div style={{ padding: '10px', borderTop: '1px solid #eee' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                    <Button
                      size="small"
                      onClick={() => setShowEmojiPicker(!showEmojiPicker)}
                    >
                      😊
                    </Button>
                    <Input
                      value={inputMsg}
                      onChange={setInputMsg}
                      onKeyPress={e => e.key === 'Enter' && sendMessage()}
                      placeholder="输入消息..."
                      style={{ '--text-align': 'left', flex: 1 }}
                    />
                    <Button
                      color="primary"
                      size="small"
                      onClick={sendMessage}
                    >
                      发送
                    </Button>
                  </div>
                  <Popup
                    visible={showEmojiPicker}
                    onMaskClick={() => setShowEmojiPicker(false)}
                    bodyStyle={{
                      borderTopLeftRadius: '8px',
                      borderTopRightRadius: '8px',
                      minHeight: '40vh'
                    }}
                  >
                    <EmojiPicker onEmojiClick={onEmojiClick} />
                  </Popup>
                </div>
              </>
            ) : (
              <div style={{ 
                display: 'flex', 
                justifyContent: 'center', 
                alignItems: 'center', 
                height: '100%',
                color: '#999'
              }}>
                请选择聊天对象
              </div>
            )}
          </div>
        </>
      ) : (
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          width: '100%',
          height: '100%'
        }}>
          <Button color='primary' onClick={() => navigate('/login')}>
            请先登录
          </Button>
        </div>
      )}
    </div>
  );
};

export default Message;